<?php

namespace App\Admin\Http\Controllers\Gift;

use Flash;
use App\Admin\Eloquent\GiftActivity;
use App\Admin\Eloquent\GiftAttr;
use App\Admin\Eloquent\GiftReceive;
use App\Eloquent\TradeRecords;
use App\Admin\Eloquent\User;
use App\Eloquent\User as Pusers;
use App\Admin\Http\Controllers\Controller;
use App\Extensions\Pagination\BootstrapThreePresenter;
use \Illuminate\Http\Request;
use App\Admin\Http\Requests\GiftActivityRequest;
use DB;
use Log;
use Exception;
use CreateHostingCollectTrade;

class ActivityController extends Controller
{
	/**
	 * 查询红包活动信息
	 * @param  Request $request [description]
	 * @return \Illuminate\Http\Response
	 */
	public function index(Request $request)
	{
		$query = $request->only('search');
		$list = GiftActivity::paging_query($query);

    if (!empty($query)) {$list->appends($query);}

		$links = (new BootstrapThreePresenter($list))->render();

		return view('admin.gift.activity.index', compact('list', 'links', 'query'));
	}

	/**
	 * 新增红包活动
	 * @return \Illuminate\Http\Response
	 */
	public function create()
	{
		$types=GiftActivity::getTypes();
		$cates=GiftActivity::getCates();
		$rules=GiftActivity::getRules();
		$grants=GiftActivity::getGrants();
		return view('admin.gift.activity.create',compact('types','cates','rules','grants'));
	}

	/**
	 * 新增红包活动
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function store(GiftActivityRequest $request)
	{
		try {
			DB::beginTransaction();

			$data=$request->input();
			$data['total_money']=$data['total_money'];
			//判断活动开始/结束时间
			if($data['end_time']<=$data['begin_time']){
				throw new Exception("活动时间错误");
			}
			//判断红包有效期
			if(isset($data['effect_time1']) && isset($data['effect_time2']) && $data['effect_time2']<=$data['effect_time1']){
				throw new Exception("红包有效期时间错误");
			}
			//添加红包活动
			$gift = new GiftActivity($data);
			$gift->save();
			//添加活动属性
			$data['activity_id']=$gift->id;
			if(isset($data['son']) || isset($data['tou'])){
				$gift_attr=new GiftAttr();
				$gift_attr->addAttr($data);
			}

			DB::commit();
			Flash::success('新增红包活动成功');
			return $this->redirectAction('Gift\ActivityController@index');
		} catch (Exception $e) {
			Flash::error('新增红包活动失败!'.$e->getMessage());
			return $this->redirectAction('Gift\ActivityController@create');
			DB::rollback();
		}
	}

	/**
	 * 编辑红包活动
	 * 
	 * @param  mixed $id
	 * @return \Illuminate\Http\Response
	 */
	public function edit($id)
	{
		$info=GiftActivity::findOrFail($id);
		$types=GiftActivity::getTypes();
		$cates=GiftActivity::getCates();
		$rules=GiftActivity::getRules();
		$grants =GiftActivity::getGrants();
		return view('admin.gift.activity.edit', compact('info','types','cates','rules','grants'));
	}
	/**
	 * 编辑红包活动
	 * 
   * @param  mixed  $id
   * @param  \App\Admin\Http\Requests\CodeRequest $request
   * @return \Illuminate\Http\Response
   * @throws \App\Exceptions\BusinessException
	 */
	public function update(GiftActivityRequest $request,$id)
	{

		$activity = GiftActivity::findOrFail($id);
		$data=$request->input();
		$data['activity_id']=$activity->id;
		$data['total_money']=$data['total_money'];
		
		$activity->update($data);

		if(isset($data['tou']) || isset($data['son'])){
			$gift_attr=new GiftAttr();
			$gift_attr->addAttr($data);
		}

		Flash::success('编辑红包活动成功');

		return $this->redirectAction('Gift\ActivityController@index');
	}

	/**
	 * 查看红包活动
	 * 
     * @param  mixed  $id
	 * @return \Illuminate\Http\Response
	 */
	public function show($id)
	{
		$info=GiftActivity::findOrFail($id);
		return view('admin.gift.activity.show', compact('info'));
	}

	/**
	 * 启用/结束 活动
	 * 
     * @param  mixed  $id
	 * @return [type] [description]
	 */
	public function start($id){
		$info=GiftActivity::findOrFail($id);
		if($info->status){
			//结束活动
			$info->update(array('status'=>3));
		}else{
			//启用活动,同一规则下启用的红包活动只能有一个(注册,定向除外)
			if($info->grant_rule!='gift_grant_rule_1' && $info->grant_rule!='gift_grant_rule_4' && GiftActivity::where('grant_rule',$info->grant_rule)->where('status',1)->first()){
					abort(600,'同一规则下启用的红包活动只能有一个(注册,定向除外)');
			}
			$info->update(array('status'=>1));
		}
		Flash::success('操作成功');
		return $this->redirectAction('Gift\ActivityController@index');
	}
	/**
	 * 发放定向红包
	 * @return [type] [description]
	 */
	public function receive(){
		$activities=GiftActivity::where('status','=',1)
		->where('begin_time','<',date('Y-m-d H:i:s'))
		->where('grant_rule','=','gift_grant_rule_4')
		->get();
		$users=User::join('user_info','user_info.user_id','=','users.id')->get();

		return view('admin.gift.activity.receive',compact('activities','users'));
	}
	/**
	 * 发放红包
	 */
	public function send(Request $request){
		try {
			DB::beginTransaction();
			$data=$request->input();
			$insert_data=array();
			$input_time=date('Y-m-d H:i:s');
			//红包活动
			$activity=GiftActivity::findOrFail($data['activity_id']);
			if($activity->status!=1){
	      throw new Exception("红包活动未启用或已结束");
	    }

	    if(time()>strtotime($activity->end_time)){
	      throw new Exception("红包活动已结束");
	    }
			//红包有效时间
			if(!empty($activity->effect_day)){
				$begin_time=$input_time;
				$end_time=date('Y-m-d H:i:s',strtotime('+'.$activity->effect_day.' day'));
			}else{
				$begin_time=$activity->effect_time1;
				$end_time=$activity->effect_time2;
			}
			//如果是现金红包,无有效期,默认使用时间
			$use_time='';
			if($activity->type_id=='gift_activity_type_2'){
				$end_time=null;
				$use_time=$input_time;
			}
			//要发放的用户
			if($data['grant_type']==0){
				$data['user_id']=User::lists('id');//全部用户
			}
			if($data['grant_type']==2){
				$data['user_id']=User::whereNotNull('last_invest_at')->lists('id');//已投资用户
			}
			if(empty($data['user_id'])){throw new Exception("请选择要发放的用户");}
			//红包发放记录
			foreach ($data['user_id'] as $user_id) {
				$row=$data;
				unset($row['_token']);
				unset($row['grant_type']);
				$row['begin_time']=$begin_time;
				if($end_time){
					$row['end_time']=$end_time;
				}
				$row['user_id']=$user_id;
				$row['activity_type']=$activity->type_id;
				$row['input_time']=$input_time;
				if($use_time){
					$row['use_time']=$use_time;
				}
			  //添加发放记录
			  $gift_receive=new GiftReceive($row);
    		$gift_receive->save();
    		//新浪发送现金红包
		    if($activity->type_id=='gift_activity_type_2'){
		    	GiftActivity::sendMoney([$user_id],$data['money'],$gift_receive->id);
		    }
			}

			$total_money=$data['money']*count($data['user_id']);
	    if($total_money+$activity->used_money>$activity->total_money){
	      throw new Exception("红包活动金额不足");
	    }
	    //更新红包活动已使用金额
	    GiftActivity::where('id','=',$activity->id)->increment('used_money',$total_money);
      //金额发放完成，修改活动状态
    	if($total_money+$activity->used_money==$activity->total_money){
	    	$activity->status=2;
	    	$activity->save();
	    }

			DB::commit();
			Flash::success('发放成功');
			return $this->redirectAction('Gift\RecordController@index',[$activity]);
		} catch (Exception $e) {
			DB::rollback();
			Flash::error('发放失败!'.$e->getMessage());
			return $this->redirectAction('Gift\ActivityController@receive');
		}
	}

	/**
	 * 获取发放规则
	 */
	public function getRule(Request $q){
		$activity_id=$q->input("activity_id");
		$attrs=array();
		if($activity_id){
			$data=GiftAttr::where("activity_id","=",$activity_id)->get();
			foreach ($data->toArray() as $key=>$item) {
				$attrs[$item['name']]=$item['value'];
			}
		}
		$auto=0;
		if(isset($attrs['auto'])){
			$auto=$attrs['auto'];
			unset($attrs['auto']);
		}
		$rule=$this->grantRule($q->input('id'));
		return view('admin.gift.activity.rule.'.$rule,compact("attrs","auto"));
	}
	/**
	 * 返回红包规则模板
	 * @return [type] [description]
	 */
	protected function grantRule($str){
		$rules=array(
			1=>array('gift_grant_rule_1','gift_grant_rule_2','gift_grant_rule_5','gift_grant_rule_6','gift_grant_rule_7'),//送XX
			3=>array('gift_grant_rule_3','gift_grant_rule_8'),//投xx,送xx
			4=>array('gift_grant_rule_4'),//定向
		);
		$rule=0;
		foreach($rules as $key=>$item){
			if(in_array($str,$item)){
				$rule=$key;
				break;
			}
		}
		return 'gift_grant_rule_'.$rule;
	}

	/**
	 * 展示发放规则
	 * @param  [type] $id [description]
	 */
	public function showRule($id){
		$activity=GiftActivity::find($id);
		$attrs=array();
		$data=GiftAttr::where("activity_id","=",$activity->id)->get();
		foreach ($data->toArray() as $key=>$item) {
			$attrs[$item['name']]=$item['value'];
		}
		$auto=0;
		if(isset($attrs['auto'])){
			$auto=$attrs['auto'];
			unset($attrs['auto']);
		}
		$rule=$activity->returnRule();
		return view('admin.gift.activity.detail_rule.gift_grant_rule_'.$rule,compact("attrs","auto"));
	}
}
